<script setup> 
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { queryPageApi, addGameCategoryApi, queryInfoApi, updateGameCategoryApi, deleteGameCategoryApi } from '@/api/gameCategory'

//游戏分类列表数据
const categoryList = ref([])

const searchCategory = ref({
  name: ''
})

onMounted(async () => {
  handleSearch()
})

//查询游戏分类
const handleSearch = async () => {
  console.log('Search:', searchCategory.value)
  const result = await queryPageApi(searchCategory.value.name, currentPage.value, pageSize.value);
  if(result.code === 1){
    categoryList.value = result.data.records
    total.value = result.data.total
  }
}

const handleReset = () => {
  // 清空表单
  searchCategory.value = {
    name: ''
  }
  handleSearch()
}

// 分页配置
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  handleSearch()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  handleSearch()
}

// 操作处理
const handleEdit = async (id) => {
  console.log('Edit:', id)
  try {
    const result = await queryInfoApi(id);
    if(result.code){
      dialogVisible.value = true
      dialogTitle.value = '修改游戏分类'
      // 深拷贝数据，确保包含id字段用于后续的更新操作判断
      category.value = {
        ...result.data,
        id: id // 明确确保id字段存在
      }
      // 注意：resetFields需要在数据设置之后调用，且确保表单引用已存在
      if (categoryFormRef.value) {
        categoryFormRef.value.resetFields()
      }
    } else {
      ElMessage.error('获取分类信息失败')
    }
  } catch (error) {
    console.error('编辑操作出错:', error)
    ElMessage.error('编辑过程中发生错误')
  }
}

// 删除单个游戏分类
const handleDelete = async (id) => {
  //弹出一个确认框, 如果确认, 就删除;
  ElMessageBox.confirm('确定删除该游戏分类吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 删除游戏分类
    const result = await deleteGameCategoryApi(id);
    if(result.code === 1){
      ElMessage.success('删除游戏分类成功') 
      handleSearch()
    }else{
      ElMessage.error(result.msg || '删除失败')
    }
  })
}

//新增游戏分类
const addCategory = () => {
  dialogVisible.value = true
  dialogTitle.value = '新增游戏分类'
  category.value = {
    id: undefined, // 明确设置为undefined表示新增操作
    name: '',
    description: ''
  }
  // 确保表单引用已存在再调用resetFields
  if (categoryFormRef.value) {
    categoryFormRef.value.resetFields()
  }
}

//新增/修改表单
const categoryFormRef = ref(null)
const category = ref({
  id: undefined, // 初始化id字段，用于更新操作判断
  name: '',
  description: ''
})

//表单校验规则
const rules = ref({
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分类名称长度应在1到50个字符之间', trigger: 'blur' }
  ]
});

// 控制弹窗状态
const dialogVisible = ref(false)
const dialogTitle = ref('新增游戏分类')

//保存游戏分类信息
const save = async () => {
  // 确保表单校验通过
  categoryFormRef.value.validate(async valid => {
    if(valid){ // 校验通过
      let result;
      try {
        // 明确判断是否有id值，来决定执行更新还是新增操作
        console.log('Category:', category.value)
        if(category.value.id){
          console.log('执行更新操作:', category.value)
          result = await updateGameCategoryApi(category.value);
        } else {
          console.log('执行新增操作:', category.value)
          result = await addGameCategoryApi(category.value);
        }
        
        if(result.code === 1){
          ElMessage.success(category.value.id ? '更新游戏分类成功' : '新增游戏分类成功')
          dialogVisible.value = false
          handleSearch() // 重新查询列表数据
        } else { 
          ElMessage.error(result.msg || '保存失败')
        }
      } catch (error) {
        console.error('保存出错:', error)
        ElMessage.error('保存过程中发生错误')
      }
    }
  })
}


</script>
<template> 
<h1>游戏分类管理</h1> <br>
  <el-form :inline="true" :model="searchCategory">
    <el-form-item label="分类名称">
      <el-input v-model="searchCategory.name" placeholder="请输入分类名称"></el-input>
    </el-form-item>
    
    <el-form-item>
      <el-button type="primary" @click="handleSearch">查询</el-button>
      <el-button @click="handleReset">清空</el-button>
    </el-form-item>
  </el-form>


  <el-button type="primary" @click="addCategory"> + 新增分类</el-button>
  <br><br>

  <!-- 表格 -->
  <el-table :data="categoryList" border style="width: 100%">
    <el-table-column prop="name" label="分类名称" width="150" align="center"></el-table-column>
    <el-table-column prop="description" label="分类描述" align="center">
      <template #default="scope">
        {{ scope.row.description || '-' }}
      </template>
    </el-table-column>
    <el-table-column label="操作" fixed="right" align="center" width="150">
      <template #default="scope">
        <el-button size="small" type="primary" @click="handleEdit(scope.row.id)">编辑</el-button>
        <el-button size="small" type="danger" @click="handleDelete(scope.row.id)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <br>

  <!-- 分页 -->
  <el-pagination
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
    :current-page="currentPage"
    :page-sizes="[10, 20, 30, 40]"
    :page-size="pageSize"
    layout="total, sizes, prev, pager, next, jumper"
    :total="total"
  >
  </el-pagination>

  <!-- 新增/修改游戏分类的对话框 -->
  <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form ref="categoryFormRef" :model="category" :rules="rules" label-width="80px">
        <el-form-item label="分类名称" prop="name">
          <el-input v-model="category.name" placeholder="请输入分类名称"></el-input>
        </el-form-item>
        
        <el-form-item label="分类描述">
          <el-input 
            v-model="category.description" 
            placeholder="请输入分类描述（可选）"
            type="textarea"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>

      <!-- 底部按钮 -->
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="save">保存</el-button>
        </span>
      </template>
  </el-dialog>

</template>
<style scoped> 
/* 可以根据需要添加自定义样式 */
</style>